import pandas as pd
import time
import traceback
from DrissionPage import Chromium, ChromiumOptions, SessionOptions
from DrissionPage.common import Settings
import schedule
from loguru import logger
from read_search_file import  get_complete_sheet1

# ========== 全局配置 ==========
Settings.set_language("zh_cn")
co = ChromiumOptions(read_file=False)
so = SessionOptions(read_file=False)
browser = Chromium(addr_or_opts=co, session_options=so)

# ========== 日志工具 ==========
def log_message(log_callback, message, color=None):
    if callable(log_callback):
        log_callback(message, color) if color else log_callback(message)

def is_number(value):
    return isinstance(value, (int, float))

# ========== 核心功能函数 ==========
def modify_budget(curr_account_id, curr_account_name, delta, log_callback=None):
    """
    调整预算：delta 可为 +0.1 或 -0.1
    """
    try:
        logger.info(f'正在调整预算 - 子账号ID: 【{curr_account_id}】 - 子账号名称: 【{curr_account_name}】')
        tab = browser.latest_tab
        # 打开合作伙伴平台页面
        tab.get('https://partner.xiaohongshu.com/partner/subAccount-list')

        tab.ele('tag:input@@class=el-input__inner@@type=text@@autocomplete=off@@placeholder=请输入').input(str(curr_account_id).strip(), clear=True)
        tab.ele('tag:button@@id=search-btn--1').click(by_js=True)

        time.sleep(2)

        search_none_ele = tab.ele('tag:tr@@class=d-table__empty-row@@text()=暂无数据', timeout=0.5)
        if search_none_ele:
            log_message(log_callback, f"合作伙伴平台子账号ID:{curr_account_id}搜索结果为空, 检查表格第一行子账号ID, 或者检查是否登录合作伙伴平台", "red")
            return

        jg_ele = tab.ele('tag:span@@class=d-text --color-static --color-current --size-text-paragraph d-text-nowrap d-text-ellipsis@@text():聚光平台', timeout=2)
        create_plan_tab = jg_ele.click.for_new_tab(by_js=True)
        create_plan_tab.wait.title_change("计划列表")

        # create_plan_tab.get(f'https://ad.xiaohongshu.com/aurora/ad/manage/campaign?vSellerId={curr_account_id}')
        # create_plan_tab.wait.load_start()

        # 点击修改按钮
        create_plan_tab.ele('tag:a@@class^d-text d-link --color-primary --size-text-paragraph bold@@text()= 修改 ').click(by_js=True)
        time.sleep(1)

        create_plan_tab.ele('tag:span@@text()=立即生效').click(by_js=True)
        time.sleep(0.5)

        create_plan_tab.ele('tag:span@@text()=指定预算').parent(1).click(by_js=True)
        time.sleep(0.5)
        # 获取当前预算
        budget_input = create_plan_tab.ele('tag:input@@class=d-text@@placeholder=请输入日预算')
        budget_num = float(budget_input.attr('aria-valuenow'))

        if budget_num != 0:
            # 修改预算
            new_budget = round(budget_num + delta, 2)
            budget_input.input(str(new_budget), clear=True)
            action = "增加" if delta > 0 else "减少"
            log_message(log_callback, f'✅ 预算已{action}{abs(delta)}元，新预算为 {new_budget}', "green")
            logger.success(f'✅ 预算已{action}{abs(delta)}元，新预算为 {new_budget}')
            create_plan_tab.ele('tag:span@@text()= 保存设置 ').parent(2).click(by_js=True) #点击保存
            time.sleep(0.3)
            browser.close_tabs(create_plan_tab)
        else:
            create_plan_tab.ele('tag:span@@text()= 取消 ').parent(2).click(by_js=True)
            browser.close_tabs(create_plan_tab)

    except Exception as e:
        error_msg = f'❌ 调整预算失败: {str(e)}\n{traceback.format_exc()}'
        log_message(log_callback, error_msg, "red")
        logger.error(error_msg)


def daily_task(delta, file_path=None, log_callback=None):
    """
    每日执行的任务：遍历 Excel 文件中所有子账号，调整预算
    :param file_path:
    :param delta: 要增减的值，+0.1 表示增加，-0.1 表示减少
    """
    df_sheet = get_complete_sheet1(file_path)

    if not df_sheet.empty:
        for index, dd in enumerate(df_sheet.itertuples()):
            curr_account_id = dd.子账户ID.strip() if pd.notna(dd.子账户ID) else ''
            curr_account_name = dd.账户名.strip() if pd.notna(dd.账户名) else ''

            log_message(log_callback, f'正在调整第【{index+1}】条数据 - 子账号ID: 【{curr_account_id}】 - 子账号名称: 【{curr_account_name}】', "purple")
            modify_budget(curr_account_id, curr_account_name, delta, log_callback)

        log_message(log_callback, f'✅ 当前批次预算调整完成', "green")
        logger.success(f'✅ 当前批次预算调整完成')

# ========== 定时任务 ==========
def schedule_tasks(file_path=None, log_callback=None):
    # 启动定时任务
    def wrap_daily_job(fn, delta, file_path, log_callback):
        def job():
            fn(delta, file_path=file_path, log_callback=log_callback)
        return job

    # 每天 00:20 减少预算
    # schedule.every().day.at("18:15:30").do(wrap_daily_job(daily_task, -0.1, file_path, log_callback))
    schedule.every().day.at("00:20").do(wrap_daily_job(daily_task, -0.1, file_path, log_callback))

    # 每天 01:00 增加预算
    schedule.every().day.at("01:10").do(wrap_daily_job(daily_task, 0.1, file_path, log_callback))

    log_message(log_callback, '⏰ 已启动定时任务，请保持程序运行...', 'blue')
    logger.info('⏰ 已启动定时任务，请保持程序运行...')

    while True:
        schedule.run_pending()
        time.sleep(2)


if __name__ == '__main__':
    file_path = r"./123.xlsx"
    schedule_tasks(file_path=file_path)
    # daily_task(-0.1, file_path=file_path)
